package com.location.test;

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.Toast;

import com.sql.test.service.DataFormatService;
import com.sql.test.service.LocalDatabaseSerivce;
import com.worldwind.test.GeometryCreator;

import java.util.ArrayList;

import gov.nasa.worldwind.WorldWind;
import gov.nasa.worldwind.WorldWindow;
import gov.nasa.worldwind.geom.Camera;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.geom.Vec3;
import gov.nasa.worldwind.globe.Globe;
import gov.nasa.worldwind.layer.RenderableLayer;
import gov.nasa.worldwind.shape.Label;
import gov.nasa.worldwind.shape.Path;
import gov.nasa.worldwind.shape.Placemark;

/**
 * Created by Lenovo on 2018/4/28.
 */

public class LocationService {


    private WorldWindow wwd= null;
    private  Activity activity = null;
    private GeometryCreator geometryCreator = new GeometryCreator();

    //添加当前位置的图层
    private RenderableLayer layer = null;
    //由于该图层是可选的，所以，不用构造函数进行传参实例化该类，用轨迹记录方法即可
    private RenderableLayer routeLayer = null;
    //简单起见，我们用一个变量来记录轨迹数据好了
    ArrayList<Position> routePositions = null;
    private LocationManager lm;
    private  LocListener locListener = null;
    private  RouteLocListener routeLocListener =null;

    //记录路程
    double distance = 0;
    Position prePosition = null;
    Position currentPosition = null;
    Vec3 prePoint,currentPoint;
    private LocalDatabaseSerivce databaseSerivce = new LocalDatabaseSerivce();
    private  DataFormatService dataFormatService = new DataFormatService();
    public LocationService(Activity activity,WorldWindow wwd ,RenderableLayer layer){
        this.activity = activity;
        this.wwd=wwd;
        this.layer=layer;
    }

    public class LocListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            String str = "当前位置:\n";
            double latitude;
            double longitude;
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            str  = str+"纬度："+latitude+"\n经度： " +longitude;
            //绘制当前位置前清除前一个位置
            layer.clearRenderables();
            //绘制当前位置
            Placemark currentLocation = geometryCreator.createPlacemark(new Position(latitude,longitude,0),"当前位置");
            layer.addRenderable(currentLocation);
            //
            wwd.requestRedraw();
            Toast.makeText(activity.getApplicationContext(),str,Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

            Toast.makeText(activity.getApplicationContext(),"状态改变！",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onProviderEnabled(String provider) {
            Toast.makeText(activity.getApplicationContext(),"位置提供者被启用！",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onProviderDisabled(String provider) {
            Toast.makeText(activity.getApplicationContext(),"位置提供者被禁用！",Toast.LENGTH_SHORT).show();
        }
    }


    public void startLocation(){
        try {
            //change provider to NETWORK is ok！
            lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            LocationProvider lp = lm.getProvider(LocationManager.GPS_PROVIDER);
            if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                           /* Toast.makeText(getApplicationContext(),"NetWork abled",Toast.LENGTH_LONG).show();*/
                locListener = new LocListener();
                lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,locListener);
                Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location == null) {
                    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
                } else {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    String str = "当前位置\n纬度：" + latitude + "\n经度： " + longitude;

                    //初始化显示视图到上一次定位位置
                    Globe globe = wwd.getGlobe();
                    Camera camera = new Camera();
                    camera.set(latitude,longitude, 2500, WorldWind.ABSOLUTE, 0, 0, 0.0 /*roll*/);
                    wwd.getNavigator().setAsCamera(globe, camera);
                    wwd.requestRedraw();

                    Toast.makeText(activity.getApplicationContext(), str, Toast.LENGTH_SHORT).show();
                }
            }else{
                Toast.makeText(activity.getApplicationContext(),"GPS Unabled",Toast.LENGTH_SHORT).show();
            }
        }catch (SecurityException e){
            e.printStackTrace();
        }
    }


    //以下定义轨迹记录的监听类和开启轨迹记录的方法,以及结束定位的方法，移除监听
    public class RouteLocListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            String str = "当前位置:\n";
            double latitude;
            double longitude;
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            str  = str+"纬度："+latitude+"\n经度： " +longitude;
            //存储数据
            currentPosition = new Position(latitude,longitude,0);
            routePositions.add(currentPosition);
            //计算路程
            //前一个点
            if(prePosition==null) {
                prePosition = currentPosition;
            }
            //前一个点，转笛卡尔坐标
            prePoint =new Vec3();
            prePoint=wwd.getGlobe().geographicToCartesian(prePosition.latitude,prePosition.longitude,prePosition.altitude,prePoint);
            //当前点,转笛卡尔坐标
            currentPoint = new Vec3();
            currentPoint=wwd.getGlobe().geographicToCartesian(currentPosition.latitude,currentPosition.longitude,currentPosition.altitude,currentPoint);
            double pointDistance = databaseSerivce.calculateDistance(prePoint,currentPoint);

            distance += pointDistance;
            //完成量算，当前点设置为前一个点，准备计算下一段距离
            prePoint = currentPoint;
            //绘制前清除之前绘制的轨迹
            routeLayer.clearRenderables();
            //绘制轨迹
            Path route = geometryCreator.createPolyline(routePositions);
            //绘制路程标注
            Label distanceLabel = geometryCreator.createLabel(currentPosition,String.valueOf(distance));
            routeLayer.addRenderable(route);
            routeLayer.addRenderable(distanceLabel);
            wwd.requestRedraw();
            Toast.makeText(activity.getApplicationContext(),str,Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

            Toast.makeText(activity.getApplicationContext(),"状态改变！",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onProviderEnabled(String provider) {
            Toast.makeText(activity.getApplicationContext(),"位置提供者被启用！",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onProviderDisabled(String provider) {
            Toast.makeText(activity.getApplicationContext(),"位置提供者被禁用！",Toast.LENGTH_SHORT).show();
        }
    }

    /**开始轨迹记录*/
    public void startRouteLocation(RenderableLayer routeLayer) {
        try {
            //图层传参，赋值，以便在图层上绘制轨迹
            this.routeLayer = routeLayer;
            //实例化用于记录数据
            routePositions = new ArrayList<>();
            //change provider to NETWORK is ok！
            lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            LocationProvider lp = lm.getProvider(LocationManager.GPS_PROVIDER);
            if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                routeLocListener = new RouteLocListener();
                /** @param provider the name of the provider with which to register
                 * @param minTime minimum time interval between location updates, in milliseconds
                 * @param minDistance minimum distance between location updates, in meters
                 * @param listener a {@link LocationListener} whose
                 * {@link LocationListener#onLocationChanged} method will be called for
                 * each location update  **/
                lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, routeLocListener);
                Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location == null) {
                                  /*  Toast.makeText(getApplicationContext(), "update location", Toast.LENGTH_LONG).show();*/
                    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, routeLocListener);
                } else {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    String str = "当前位置\n纬度：" + latitude + "\n经度： " + longitude;
                    Toast.makeText(activity.getApplicationContext(), str, Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(activity.getApplicationContext(), "GPS Unabled", Toast.LENGTH_SHORT).show();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }
    /**移除轨迹监听*/
    public void stopRouteLocation(){
        //移除轨迹监听
        lm.removeUpdates(routeLocListener);
    }
    /**删除轨迹*/
    public void deleteRoute(){
        routeLayer.clearRenderables();
        wwd.requestRedraw();
    }

}
